package com.wlcb.jpower.chat.server.handler;

import com.alibaba.fastjson.JSONObject;
import com.wlcb.jpower.chat.server.handler.customer.CustomerMessage;
import com.wlcb.jpower.chat.service.customer.ChatService;
import com.wlcb.jpower.constant.ChatConfigConstant;
import com.wlcb.jpower.constant.ChatConstant;
import com.wlcb.jpower.im.group.ChatChannelGroup;
import com.wlcb.jpower.im.model.DataPacket;
import com.wlcb.jpower.im.cache.SessionCache;
import com.wlcb.jpower.module.common.utils.Fc;
import com.wlcb.jpower.module.common.utils.SpringUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 聊天信息处理类
 */
@Slf4j
@ChannelHandler.Sharable
public class ChatServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        Channel channel = ctx.channel();
        DataPacket dataPacket = JSONObject.parseObject(msg.text(), DataPacket.class);
        if (!Fc.isNull(dataPacket) && ChatConstant.ChatActionEnum.HEARTBEAT.type.intValue() != dataPacket.getAction()) {
            MessageHandler messageHandler = CustomerMessage.getInstance().getChatHandler(dataPacket.getAction());
            if (Fc.isNull(messageHandler)) {
                log.error("未找到该指令：action：{}", dataPacket.getAction());
                return;
            }
            messageHandler.handler(ctx,dataPacket);
            //MessageActuator.getInstance(messageHandler).run(ctx, dataPacket);
        } else {
            channel.writeAndFlush(new TextWebSocketFrame(dataPacket.toString()));
            SessionCache.reUserTime(channel);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.debug("websocket server get connect");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            ChatService chatService = SpringUtil.getBean(ChatService.class);
            log.debug("Handshake has completed");
            List<DataPacket.Wait> waitUsers = chatService.getWaitUsers();
            DataPacket dataPacket = DataPacket.wait(waitUsers, ChatConfigConstant.UserType.CUSTOMER);
            ctx.channel().writeAndFlush(new TextWebSocketFrame(dataPacket.toString()));
        } else if (evt instanceof IdleStateEvent) {
            // 判断evt是否是IdleStateEvent（用于触发用户事件，包含 读空闲/写空闲/读写空闲）
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                log.warn("进入读空闲...");
            } else if (event.state() == IdleState.ALL_IDLE) {
                log.warn("所有的空闲...");
                ChannelGroup users = ChatChannelGroup.CHANNELGROUP;
                log.warn("Session关闭前，users的数量为：" + users.size());
                ctx.channel().close();
                log.warn("Session关闭后，users的数量为：" + users.size());
            }
        }
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        SessionCache.remove(ctx.channel());
        log.debug("websocket server remove channel");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        log.debug("websocket server exception:{}", cause.getMessage());
    }

}
